{extend name='layout:app'}

{block name='css'}
    <link rel="stylesheet" href="__STATIC__/css/qrcode-pay.css">
    <link rel="stylesheet" href="__STATIC__/css/zhifu.css">
    <style>
        .up-enter-active, .up-leave-active{
            /*transition:all .4s cubic-bezier(0.49, -0.29, 0.75, 0.41);*/
            transition:all .4s cubic-bezier(.27,.78,.51,.91);
        }
        .balls{
            position: fixed;
            top: 75px;
            right: 33px;
            z-index: 200;
        }
        .ball-inner{
            display: inline-block;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #F56C6C;
            transition: all .4s linear;
        }
        .code-tb table{
            width: 65%;
            margin: 0 17.5%;
        }
    </style>
{/block}

{block name='content'}
<div id="app">
    <div class="nav">
        <i class="el-icon-arrow-left icon_left" @click="back"></i>
        <div>地址编辑</div>
        <i class="iconfont icon-home icon_right" @click="home"></i>
    </div>

    <div class="qr-code">
        <div class="code-tb" style="width: 100%;background-color: #34ACFF;padding: 11px 0;margin-bottom: 25px;text-align: center;justify-content: center;">
        <table border="3" style="font-size: 16px;color: white;">
            <tr>
                <td>钱包:</td>
                <td>￥{$balance}</td>
                <td>积分:</td>
                <td>{$point}</td>
            </tr>
        </table>
    </div>
        <div class="add-to-cart" style="display: none;">
            <el-badge :value="codeCount" class="item"><i class="iconfont icon-shoppingcart"></i></el-badge></div>

        <div class="cont-area">
            <div class="code-bg" style="background-color: white;">
                <img src="__STATIC__/imgs/qrcode-pay.png" alt="">
            </div>
            <div class="info">
                <div class="info-txt" style="text-align: center">生成二维码数量 <span style="font-size: 18px;font-weight: bold">1</span></div>
                <div class="outer-display" style="display: none;">
                        <span class="count-area"><span class="minus" @click="countMinus">-</span><span class="code-num">{{codeCount}}
                            <transition-group name="up" @before-enter="beforeEnter"
                                              @enter="enter"
                                              @after-enter="afterEnter">
                                <span class="balls" v-for="(ball,index) in balls" :key="index" v-show="ball.show">
                                    <span class="ball-inner"></span>
                                </span>
                            </transition-group>
                        </span><span class="add" @click="countAdd">+</span></span>
                </div>
            </div>
            <div class="tips">一个二维码只能取件一次</div>
        </div>
    </div>

    <div class="pay">
        <div class="pay-way">
<!--            余额-->
            <div class="remain" @click="choosePay($event)">
                <i class="iconfont icon-pay-order"></i>
                <span class="txt">余额支付<span style="font-size: 15px">({$balance} ￥)</span></span>
                <span class="circle-btn active-bg"></span>
            </div>
<!--            微信-->
           <div class="wechat" @click="choosePay($event)">
               <i class="iconfont icon-wechat"></i>
               <span class="txt">微信支付</span>
               <span class="circle-btn"></span>
           </div>

        </div>
        <div class="go-pay">
            <div class="pay-money">
                <span>应付款 <span class="red-txt">¥<span class="money">{{codeCount}}</span></span></span>
            </div>
            <div class="btn-pay" @click="goPay">去付款</div>
        </div>
    </div>

    <div id="modal"  v-loading="loading"
         element-loading-text="正在加载"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0,0,0,.1)"></div>
    <!--余额支付付款页面-->
    <div id="remaining">
        <!--<div class="header">
            <div class="all_w ">
                <div class="gofh">
                    <img src="__IMG__/images/jt_03.jpg" style="width:16px;">
                </div>
            </div>
        </div>
        <div class="wenx_xx">
            <div class="mz">测试商城</div>
            <div class="zhifu_price">￥88.88</div>
        </div>
        <div class="pay_by-remaining">
            <a href="javascript:void(0);" class="ljzf_but all_w">立即支付</a>
        </div>-->
        <!--浮动层-->
        <div class="ftc_wzsf">
            <div class="srzfmm_box">
                <div class="qsrzfmm_bt clear_wl">
                    <img src="__IMG__/images/xx_03.jpg" class="tx close fl" @click="payUIClose">
                    <img src="__IMG__/images/jftc_03.png" class="tx fl">
                    <span class="fl">请输入支付密码</span></div>
                <div class="zfmmxx_shop">
                    <div class="mz">取件二维码</div>
                    <div class="zhifu_price">￥{{codeCount}}</div></div>
                <ul class="mm_box" @click="numberShow">
                    <li></li><li></li><li></li><li></li><li></li><li></li>
                </ul>
            </div>
            <div class="numb_box">
                <div class="xiaq_tb" @click="numberHide">
                    <img src="__IMG__/images/jftc_14.jpg" height="10" style="width:40px;"></div>
                <ul class="nub_ggg" @click="pwdInput">
                    <li><a href="javascript:void(0);" class="zf_num">1</a></li>
                    <li><a href="javascript:void(0);" class="zj_x zf_num">2</a></li>
                    <li><a href="javascript:void(0);" class="zf_num">3</a></li>
                    <li><a href="javascript:void(0);" class="zf_num">4</a></li>
                    <li><a href="javascript:void(0);" class="zj_x zf_num">5</a></li>
                    <li><a href="javascript:void(0);" class="zf_num">6</a></li>
                    <li><a href="javascript:void(0);" class="zf_num">7</a></li>
                    <li><a href="javascript:void(0);" class="zj_x zf_num">8</a></li>
                    <li><a href="javascript:void(0);" class="zf_num">9</a></li>
                    <li><a href="javascript:void(0);" class="zf_empty">清空</a></li>
                    <li><a href="javascript:void(0);" class="zj_x zf_num">0</a></li>
                    <li><a href="javascript:void(0);" class="zf_del">删除</a></li>
                </ul>
            </div>
            <div class="hbbj"></div>
        </div>
    </div>
</div>
{/block}

{block name='footer'}{/block}

{block name='js'}
<script>
    window.onload = function () {
        var _i = 0;
        var that;
        //出现浮动层
        $(".ljzf_but").click(function(){
            $(".ftc_wzsf").show();
        });
        //关闭浮动
        $(".close").click(function(){
            $(".ftc_wzsf").hide();
            $(".mm_box li").removeClass("mmdd");
            $(".mm_box li").attr("data","");
            _i = 0;
        });
        //取消支付
        $('.gofh').click(function () {
            // $('#remaining').css({height:0,transformOrigin:'bottom',transition:'all .3s ease'});
            $('#remaining').slideUp();
        })
        //数字显示隐藏
        $(".xiaq_tb").click(function(){
            $(".numb_box").slideUp(500);
        });
        $(".mm_box").click(function(){
            $(".numb_box").slideDown(500);
        });
        new Vue({
            el:'#app',
            data: {
                loading: false,
                codeCount: '0.00',
                balance:{$balance},
                balls:[
                    {
                        show: false, el: null
                    }
                ],
                dropballs:[],
                payWay: 1,
                canPay: true,
                paypwdInput: ''
            },
            created() {
                that = this;
                console.log(that.codeCount)
                $.post('/index/services/getexpress',function (res) {
                    if(res.code === 0 && res.data.count) {
                        $('.btn-pay').css({background:'#B40606',color:'#fff'})
                        that.codeCount = that.changeTwoDecimal_f(res.data.count)
                        var fragment = `<div style="text-align: center">您当前有<em style="font-weight: bold">${res.data.count}</em>个包裹待收</div>`;
                        for(i in res.data.data) {
                            i = Math.trunc(i) + 1;
                            fragment += `<div>${i}.${res.data.data[i-1]}</div>`
                        }
                        that.$alert(fragment,'包裹信息',{
                            dangerouslyUseHTMLString: true
                        })
                    }else {
                        that.canPay = false
                        that.$alert('您当前未有包裹到驿站哦!','包裹信息',{
                            dangerouslyUseHTMLString: true,
                            center: true
                        })
                    }
                })
            },
            methods: {
                back() {
                    window.history.go(-1)
                },
                home() {
                    location.href = '/'
                },
                drop(el) {
                    for(let i = 0;i<this.balls.length;i++){
                        let ball = this.balls[i]
                        if(!ball.show){
                            ball.show = true
                            ball.el = el
                            this.dropballs.push(ball)
                            return
                        }
                    }
                },
                beforeEnter(el) {
                    let count = this.balls.length
                    let ballsEl = $('.icon-shoppingcart')[0].getBoundingClientRect()
                    // console.log(ballsEl)

                    while(count--){
                        let ball = this.balls[count]
                        if(ball.show){
                            let rect = $('.code-num')[0].getBoundingClientRect() // 获取元素视口位置
                            // console.log(rect)
                            let x = -(ballsEl.left - rect.left - 35/2)
                            let y = (rect.top - 75)
                            el.style.display = ''
                            el.style.webkitTransform = `translate3d(0,${y}px,0)`
                            el.style.transform = `translate3d(0,${y}px,0)`
                            let inner = el.getElementsByClassName('ball-inner')[0]
                            inner.style.webkitTransform = `translate3d(${x}px,0,0)`
                            inner.style.transform = `translate3d(${x}px,0,0)`
                        }
                    }
                },
                enter(el) {
                    /* eslint-disable no-unused-vars */
                    let rf = el.offsetHeight
                    this.$nextTick(() => {
                        el.style.webkitTransform = 'translate3d(0,0,0)'
                        el.style.transform = 'translate3d(0,0,0)'
                        let inner = el.getElementsByClassName('ball-inner')[0]
                        inner.style.webkitTransform = 'translate3d(0,0,0)'
                        inner.style.transform = 'translate3d(0,0,0)'
                    })
                },
                afterEnter(el) {
                    let ball = this.dropballs.shift() // 完成一次动画就删除一个dropBalls的小球
                    if (ball) {
                        ball.show = false
                        el.style.display = 'none' // 隐藏小球
                    }
                },
                countMinus() {
                    this.codeCount--
                    if(this.codeCount < 1) {
                        this.codeCount = 1
                    }
                },
                countAdd(el) {
                    this.codeCount++
                    this.drop($(el.target).siblings('.code-num'))
                },
                choosePay(e) {
                    if($(e.currentTarget).find('.circle-btn').hasClass('active-bg')) {
                        $(e.currentTarget).siblings().find('.circle-btn').removeClass('active-bg')
                    }else {
                        $(e.currentTarget).find('.circle-btn').addClass('active-bg')
                        $(e.currentTarget).siblings().find('.circle-btn').removeClass('active-bg')
                    }
                    if($(e.currentTarget).hasClass('wechat')) {
                        this.payWay = 0
                    }else {
                        this.payWay = 1
                    }
                },
                changeTwoDecimal_f(x) { //数字保留两位小数
                    var f_x = parseFloat(x);
                    if (isNaN(f_x)) {
                        alert('function:changeTwoDecimal->parameter error');
                        return false;
                    }
                    var f_x = Math.round(x * 100) / 100; //保证小数位不大于2位
                    var s_x = f_x.toString();
                    var pos_decimal = s_x.indexOf('.');
                    if (pos_decimal < 0) {
                        pos_decimal = s_x.length;
                        s_x += '.';
                    }
                    while (s_x.length <= pos_decimal + 2) {
                        s_x += '0';
                    }
                    return s_x;
                },
                goPay() {
                    if(!this.canPay) {
                        return
                    }
                    if(this.payWay === 1){
                        if(that.balance < that.codeCount) {
                            var obj = true;
                            var str = JSON.stringify(obj);
                            //存入
                            sessionStorage.obj = str;
                            this.$confirm('余额不足，请充值','提示',{
                                confirmButtonText:'确定',
                                cancelButtonText:'取消',
                                type:'warning'
                            }).then (()=>{
                                this.$message({
                                    type:'info',
                                    message:"前往充值",
                                });
                                window.location.href = '/index/services/editmoney'
                            }).catch(()=>{
                                this.$message({
                                    type:'info',
                                    message:"取消充值"
                                });
                            })
                            return
                        }
                        $.get('/index/services/checkpaypwd',function (res) {
                            if(res.code === 600) {
                                location.href = '/index/person/paypwd'
                                return false
                            }
                        },'json')
                    }

                    $('#modal').show()
                    this.loading = true
                    setTimeout(() => {
                        $('#modal').hide()
                        this.loading = false

                        //describe商品名称 orderNum订单号 id商品id num数量
                        const orderNum = that.createOrderNum()
                        if(this.payWay === 0) {
                            this.$prompt('请输入金额', '微信支付', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                inputPattern: /^[1-9]\d*$/,
                                inputErrorMessage: '金额输入不正确'
                                }).then(({ value }) => {
                                    console.log(value);
                                    if (navigator.userAgent.indexOf('MicroMessenger') != -1 && navigator.userAgent.indexOf('Mobile') != -1) {
                                        $.post('/index/payment/placeorder',{
                                            describe: '二维码取件充值',
                                            orderNum: orderNum,
                                            money: value,
                                        },function (res) {
                                            if(res) {
                                                if(typeof WeixinJSBridge == "undefined"){
                                                    if( document.addEventListener ){
                                                        document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady, false);
                                                    }else if (document.attachEvent){
                                                        document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady);
                                                        document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady);
                                                    }
                                                }else {
                                                    that.onBridgeReady(res.data, orderNum);
                                                }
                                            }else {
                                                alert('库存不足，请重新购买');
                                            }
        
                                        },'json')
        
                                        return
                                    }else{
                                        this.$message('请用手机微信访问')
                                    }
                                }).catch()
                        }else {
                            $('#remaining').slideDown();
                            $('.ftc_wzsf').show();
                        }

                    }, 500)
                },
                onBridgeReady(paramNeed, orderNum) {
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', paramNeed,
                        function(res){
                            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                                // 使用以上方式判断前端返回,微信团队郑重提示：
                                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                $.post("/index/payment/paysuccess", {
                                    orderNum: orderNum,
                                    count: that.codeCount
                                }, function (resStatus) {
                                    if(resStatus.code === 0) {
                                        window.location.href = '/index/person/mycode'
                                    }else{
                                        that.$message(resStatus.msg)
                                    }
                                },'json')
                            }
                        });
                },
                pwdInput(e) {
                    if(($(e.target).text()) == '删除') {
                        if(_i>0){
                            _i--
                            $(".mm_box li").eq(_i).removeClass("mmdd");
                            $(".mm_box li").eq(_i).attr("data","");
                            that.paypwdInput = that.paypwdInput.substr(0,_i)
                        }
                        return
                    }
                    if(($(e.target).text()) == '清空') {
                        $(".mm_box li").removeClass("mmdd");
                        $(".mm_box li").attr("data","");
                        _i = 0;
                        that.paypwdInput = ''
                        return
                    }
                    if(_i<6){
                        $(".mm_box li").eq(_i).addClass("mmdd");
                        $(".mm_box li").eq(_i).attr("data",$(e.target).text());
                        that.paypwdInput += $(".mm_box li").eq(_i).attr("data");
                        _i++
                        if (_i==6) {
                            var orderNum = this.createOrderNum()
                            setTimeout(function(){
                                $.post('/index/services/balancepay',{
                                    describe: '生成二维码余额支付',
                                    orderNum: orderNum,
                                    paypwd: that.paypwdInput
                                },function (res) {
                                    if(res.code === 0) {
                                        $.post("/index/payment/paysuccess", {
                                            orderNum: orderNum,
                                        }, function (resStatus) {
                                            if(resStatus.code === 0) {
                                                window.location.href = '/index/person/mycode'
                                            }
                                        },'json')
                                    }else {
                                        that.paypwdInput = ''
                                        $(".mm_box li").removeClass("mmdd");
                                        _i = 0;
                                        that.$message({
                                            message: res.msg,
                                            type: 'error',
                                            center: true,
                                            duration: 1000
                                        });
                                        if(res.code === 601) {
                                            $('.close').click()
                                            $('.wechat').click()
                                        }
                                    }
                                },'json')
                            },100);
                        };
                    }
                },
                createOrderNum() {
                    var t = new Date(),
                        y = t.getFullYear(),
                        mon = t.getMonth() + 1,
                        d = t.getDate(),
                        h = t.getHours(),
                        min = t.getMinutes(),
                        s = t.getSeconds()

                    if(mon<10) mon = '0'+mon
                    if(d<10) d = '0'+d
                    if(h<10) h = '0'+h
                    if(min<10) min = '0'+min
                    if(s<10) s = '0'+s

                    const orderNum = String(y)+String(mon)+String(d)+String(h)+String(min)+String(s)+that.randomNum(4)
                    return orderNum;
                },
                randomNum(n) {
                    var randomNum = ''
                    for(var i=0;i<n;i++){
                        randomNum += Math.floor(Math.random()*10)
                    }
                    return randomNum
                },
                numberShow() {
                    $(".numb_box").slideDown(500);
                },
                numberHide() {
                    $(".numb_box").slideUp(500);
                },
                payUIClose() {
                    $(".ftc_wzsf").hide();
                    $(".mm_box li").removeClass("mmdd");
                    $(".mm_box li").attr("data","");
                    _i = 0;
                }
            },
            watch: {
                codeCount: function (val, oldVal) {
                    // console.log('new:%s,old:%s',val,oldVal)
                    if(val != oldVal) {
                        $.post('',{code_amount: val},function (res) {

                        })
                    }
                }
            }
        });
    }


</script>
{/block}